<template>
  <el-container class="homeclass">
    <!-- 头部 -->
    <el-header>
      <!-- 顶部栏区域 -->
      <div class="coping-railing">
        <!-- 位置选择 -->
        <el-dropdown class="location-choice">
          <span class="el-dropdown-link">
            中国大陆<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>全球</el-dropdown-item>
            <el-dropdown-item>中国大陆</el-dropdown-item>
            <el-dropdown-item>中国香港</el-dropdown-item>
            <el-dropdown-item>中国台湾</el-dropdown-item>
            <el-dropdown-item>中国澳门</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- 登录 -->
        <span @click="dialogTableVisible = true">
          <span class="h" @click="login()" v-show="!isLogin"
            >亲亲,点这里登录</span
          >
        </span>
        <!-- 登录完成后 -->
        <el-dropdown>
          <span class="uu" v-show="isLogin">
            {{ this.username }}<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="toUserInfo()"
              >个人信息</el-dropdown-item
            >
            <el-dropdown-item @click.native="toUserAddress()"
              >收货地址</el-dropdown-item
            >
            <el-dropdown-item @click.native="loginStaClose()"
              >退出</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <!-- 我的购物车 -->
        <div class="shopping-cart">
          <!-- 购物车图标 -->
          <svg
            t="1629558672372"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="6026"
            width="16"
            height="16"
          >
            <path
              d="M972.8512 247.2448a25.58976 25.58976 0 0 0-20.8896-10.8544H233.8816l-23.04-102.1952a25.58976 25.58976 0 0 0-24.9856-19.968H79.9744c-14.1312 0-25.6 11.4688-25.6 25.6s11.4688 25.6 25.6 25.6H165.376l22.9888 102.144v0.0512l68.7616 305.3056v0.0512l31.7952 141.1584c2.6112 11.6736 13.0048 19.968 24.9856 19.968h491.52c14.1312 0 25.6-11.4688 25.6-25.6s-11.4688-25.6-25.6-25.6h-471.04l-20.2752-89.9584h529.2032c10.8544 0 20.48-6.8096 24.1152-17.0496l108.4928-305.3056c2.9184-7.8336 1.6896-16.5376-3.072-23.3472z m-435.3024 131.328H333.6192c-14.1312 0-25.6-11.4688-25.6-25.6s11.4688-25.6 25.6-25.6h203.9296c14.1312 0 25.6 11.4688 25.6 25.6s-11.4688 25.6-25.6 25.6z"
              fill="#FF623E"
              p-id="6027"
            ></path>
            <path
              d="M358.1952 844.5952m-59.3408 0a59.3408 59.3408 0 1 0 118.6816 0 59.3408 59.3408 0 1 0-118.6816 0Z"
              fill="#FF623E"
              p-id="6028"
            ></path>
            <path
              d="M769.9968 844.5952m-59.3408 0a59.3408 59.3408 0 1 0 118.6816 0 59.3408 59.3408 0 1 0-118.6816 0Z"
              fill="#FF623E"
              p-id="6029"
            ></path>
          </svg>
          <span class="spanclass" @click="toTrolley"> 我的购物车 </span>
        </div>
        <!-- 我的订单 -->
        <span class="orderclass" @click="order"> 我的订单 </span>
      </div>
      <tr>
        <td>
          <img src="../assets/就购.png" alt="" class="imgclass" @click="home" />
        </td>
        <td class="searchClass">
          <el-input placeholder="请输入内容" v-model="select" clearable>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
            <el-dropdown slot="suffix" style="padding: 10px 0">
              <span class="el-dropdown-link" style="color: #c0c6d7">
                宝贝<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>宝贝</el-dropdown-item>
                <el-dropdown-item>店铺</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              style="color: #ff8a00"
              slot="append"
              @click="SelectOne(select)"
              >搜索</el-button
            >
          </el-input>
        </td>
      </tr>
    </el-header>
    <!-- 主体 -->
    <el-main :style="defaultHeight">
      <router-view></router-view>
    </el-main>
    <!-- 底部 -->
    <el-footer>
      <div id="font">
        <a href="https://beian.miit.gov.cn/" target="_blank">
          桂ICP备2020008918号-1</a
        >
        |
        <img
          src="https://cdn.jsdelivr.net/gh/fufu0al/Img/img/%E5%A4%87%E6%A1%88%E5%9B%BE%E6%A0%87.png"
        /><a
          target="_blank"
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=35080202351185"
          >闽公网安备 35080202351185号</a
        >
      </div>
    </el-footer>
    <!-- 登录对话框 -->
    <el-dialog
      :visible.sync="dialogTableVisible"
      @close="loginDialogclosed"
      width="500px"
      style="text-align: center"
    >
      <!-- 登录表单 -->
      <el-form
        :model="loginForm"
        :rules="loginFormRules"
        ref="loginFormRef"
        label-width="70px"
      >
        <el-form-item label="账号" prop="username">
          <el-input
            type="username"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 提交、重置按钮 -->
        <el-button size="mini" type="success" plain @click="submitForm()"
          >登录</el-button
        >
        <el-button size="mini" type="warning" plain @click="resetLoginForm()"
          >取消</el-button
        >
        <span class="span-a" @click="register">没有账号？点击注册</span>
      </el-form>
    </el-dialog>
    <!-- 注册对话框 -->
    <el-dialog
      :visible.sync="registerVisible"
      @close="registerDialogclosed"
      :showClose="showClo"
    >
      <el-form
        label-width="100px"
        :model="registerForm"
        :rules="registerFormRules"
        ref="registerFormRef"
      >
        <el-form-item label="昵称" prop="NickName">
          <el-input v-model="registerForm.NickName"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkpassword">
          <el-input v-model="registerForm.checkpassword"></el-input>
        </el-form-item>
        <!-- E-mail -->
        <el-form-item prop="mailbox" label="邮箱">
          <el-input v-model="registerForm.mailbox"></el-input>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone"></el-input>
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="Sex">
          <el-radio v-model="registerForm.Sex" label="1" style="margin: 0px"
            >男</el-radio
          >
          <el-radio
            v-model="registerForm.Sex"
            label="2"
            style="margin-left: 1rem"
            >女</el-radio
          >
        </el-form-item>
        <!-- 年龄 -->
        <el-form-item label="年龄" prrp="Age">
          <el-input-number
            v-model="registerForm.Age"
            :step="2"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button
          size="mini"
          type="success"
          plain
          @click="RegisterOne()"
          class="btnclass"
          >注册</el-button
        >
        <el-button
          size="mini"
          type="warning"
          plain
          @click="cancel()"
          class="btnclass"
          >取消</el-button
        >
      </span>
    </el-dialog>

    <!-- Dialog 收货地址 -->
    <el-dialog
      title="收货地址"
      :visible.sync="userAddressDialogVisible"
      width="30%"
      center
    >
      <el-form
        ref="form"
        label-width="80px"
        style="padding-left: 3rem"
        :data="userShipAddress"
      >
        <el-form-item label="收货地址">
          <template>
            <el-select
              v-model="userShipAddress.shipValue"
              placeholder="请选择你的收货地址"
            >
              <el-option
                v-for="item in shipOptions"
                :key="item.id"
                :label="item.addAddress"
                :value="item.addAddress"
              >
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="添加地址">
          <template>
            <el-input
              v-model="userShipAddress.addAddress"
              placeholder="请输入要添加的地址"
            ></el-input>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userAddressDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleSave(userShipAddress.addAddress)"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
// Dialog 
import { Login } from "../api/home"
import { AddUsers, SeleteAdd, Address, GetAddress } from '../api/home'
import { getRefresh } from "../Utils/auth"
// Dialog END

export default {
  mounted () {
    this.reloadLoginInfo();
    this.getUserAddress();
  },
  data () {

    // 自定义验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 正确的邮箱
        return cb()
      }
      cb(new Error('请输入正确的邮箱'))
    }
    // 自定义验证手机号规则
    var checkMobile = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^1[3-9]\d{9}$/
      if (regMobile.test(value)) {
        // 验证通过
        return callback()
      } else {
        // 验证不通过，返回提示信息
        return callback(new Error('请输入正确的手机号'))
      }
    }
    return {
      // 用户收货地址列表数据
      shipOptions: [],
      addUserAddress: [],
      userShipAddress: {
        addAddress: ''
      },

      defaultHeight: {
        height: ""
      },
      selectFrist: {},
      input: '',
      // Dialog 
      dialogTableVisible: false,
      loginForm: {
        username: "",
        password: "",
      },
      //   登录表单验证
      loginFormRules: {
        //   验证用户名
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 用户收货地址Dialog
      userAddressDialogVisible: false,
      // Dialog End
      showClo: false,
      // 注册对话框的显示和隐藏
      registerVisible: false,
      // 性别数据  1: 男， 2: 女
      radio: '1',
      // 注册表单
      registerForm: {
        NickName: "",
        username: "",
        password: "",
        checkpassword: "",
        phone: "",
        mailbox: "",
        Sex: " ",
        Age: " ",
      },
      // 注册表单验证
      registerFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 7, message: "长度在 3 到7 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 12, message: "长度在 6 到 12 个字符", trigger: "blur" },
        ],
        checkpassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { min: 6, max: 12, message: "长度在 6 到 12 个字符", trigger: "blur" },
        ],
        mailbox: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
      },
      isLogin: false,
      username: 'asdfa',
      isReload: true,
      imgList: [
        { url: require("../assets/logo.png") },
        { url: require("../assets/logo.png") },
      ],
      select: "",
    };
  },
  methods: {
    SelectOne (name) {
      this.selectFrist = {
        "CommodityName": name
      }
      console.log(this.selectFrist);
      SeleteAdd(this.selectFrist).then(res => {
        console.log(res);
      })
    },
    //定义方法，获取高度减去头尾
    getHeight () {
      this.defaultHeight.height = window.innerHeight - 110 + "px";
    },
    //获得用户地址
    getUserAddress () {


      GetAddress(window.localStorage.getItem("Id")).then(res => {
        console.log(res);
        res.data.data.forEach(item => {
          this.shipOptions.push({
            addAddress: item.address
          })
        })
      });
    },
    home () {
      this.$router.push('/shouye')
    },
    // Dialog
    //   点击取消按钮事件
    resetLoginForm () {
      this.dialogTableVisible = false
    },
    // 监听登录对话框关闭的事件
    loginDialogclosed () {
      this.$refs.loginFormRef.resetFields()
    },
    // 监听注册对话框关闭的事件
    registerDialogclosed () {
      this.$refs.registerFormRef.resetFields()
    },
    toUserInfo () {
      this.$router.push('userinfo')
    },
    //   登录验证
    submitForm () {
      console.log(Login);
      console.log(this.loginForm);
      if (this.loginForm.username.trim() == "" || this.loginForm.password.trim() == "") {
        alert("账号或密码不能为空")
      }
      else {
        Login(this.loginForm).then((res) => {
          if (res.data.code == 1002) {
            alert("账号密码错误或改用户被封禁，请确认后重试")
          } else {
            console.log(res.data);
            alert("登录成功");
            localStorage.setItem("accessToken", res.data.data.token);
            localStorage.setItem("refreshToken", res.data.data.refreshToken)
            localStorage.setItem("Id", res.data.data.id)
            localStorage.setItem("Username", this.loginForm.username)
            this.dialogTableVisible = false
            this.loginSta()
          }
        })
      }
    },
    // 点击注册触发的事件
    register () {
      this.dialogTableVisible = false;
      this.registerVisible = true
    },
    // 取消注册
    cancel () {
      this.registerVisible = false
      this.dialogTableVisible = true
    },
    submitUpload () {
      console.log(123);
    },

    ExceededQuantity () {
      alert("抱歉，选中图片超出限制")
    },
    toInfo () {
      this.$router.push('userinfo')
    },
    // 注册
    RegisterOne: function () {
      console.log(this.registerForm);
      if (this.registerForm.NickName != '' && this.registerForm.username != '' && this.registerForm.password != '' && this.registerForm.Age != 0 &&
        this.registerForm.Sex != '' && this.registerForm.mailbox != '' && this.registerForm.phone != '') {
        this.registerForm.Sex = parseInt(this.registerForm.Sex)
        this.registerForm.phone = parseInt(this.registerForm.phone)
        if (this.registerForm.password == this.registerForm.checkpassword) {
          AddUsers(this.registerForm).then((res) => {
            console.log(res.data.data);
            alert("注册成功")
            this.$router.push({ name: "Headpicture", params: { key: res.data.data.id } });
            this.registerVisible = false;
          })
        }
        else {
          alert("请确认两次输入密码相同")
        }
      }
      else {
        alert("请确保没有任何一项为空");
      }
    },
    toHome () {
      window.$router.push('/')
    },
    // Dialog End

    // 登录状态
    loginSta () {
      let id = localStorage.getItem("Id");
      let username = localStorage.getItem("Username")
      console.log(111);
      if (id !== null && id !== undefined) {
        this.isLogin = true;
        this.username = username;
        if (this.isReload) {
          location.reload();
        }
      }
    },
    // 退出登录
    loginStaClose () {
      localStorage.removeItem("Username");
      localStorage.removeItem("Id");
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      this.$router.push('/')
      location.reload();
    },

    login () {
      this.dialogTableVisible = true;
    },
    order () {
      this.$router.push("/order");
    },
    toTrolley () {
      this.$router.push('/trolley')
    },
    reloadLoginInfo () {
      let id = localStorage.getItem("Id");
      let username = localStorage.getItem("Username")
      if (id !== null && id !== undefined) {
        this.isLogin = true;
        this.username = username;
      }
    },
    // 收货地址Dialog事件
    toUserAddress () {
      this.userAddressDialogVisible = true;
    },
    // 地址保存
    handleSave (AddressOne) {
      if (AddressOne == '') {
        alert("地址不能为空")
      }
      else {
        this.addUserAddress = {
          address: AddressOne,
          UsersId: parseInt(localStorage.getItem("Id"))
        }
        console.log(this.addUserAddress);
        Address(this.addUserAddress).then(res => {
          console.log(res);
          alert("添加成功")
        });
      }

    }
  },
  created () {
    //页面创建时执行一次getHeight进行赋值，顺道绑定resize事件
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
  }
};
</script>

<style scoped>
.homeclass {
  height: 100%;
}
.el-header {
  background-color: #eae8eb;
  height: 150px !important;
  padding: 0px;
}
.el-main {
  height: 100%;
}
.el-footer {
  background-color: #ffffff;
}
#font {
  text-align: center;
  padding: 15px 0;
}
/* 顶部栏样式 */
.coping-railing {
  background-color: #f5f5f5;
  height: 50px;
  width: 100% !important;
}
/* 位置选择 */
.location-choice {
  padding: 15px 0;
  margin-left: 7px;
}
a {
  text-decoration: none;
}
/* 登录 */
.h {
  padding: 15px 0;
  margin-left: 10px;
  color: #f22e00 !important;
  font-size: 14px;
  cursor: pointer;
}
/* 登录完成后 */
.uu {
  padding: 15px 0;
  margin-left: 10px;
  font-size: 14px;
  cursor: pointer;
}
.uu:hover {
  color: #f22e00;
}
/* logo */
.imgclass {
  margin-left: 50px;
  cursor: pointer;
}
/* 搜索框 */
.searchClass {
  margin-left: 30px;
  width: 650px;
  float: left;
  margin-bottom: 100px;
}
/* 购物车 */
.shopping-cart {
  float: right;
  padding: 15px 0;
  margin-right: 50px;
  cursor: pointer;
}
/* 购物车字体 */
.spanclass {
  margin-left: 4px;
  font-size: 13px;
  color: #b1b1b1;
}
.spanclass:hover {
  color: #f22e00;
}
/* 我的订单 */
.orderclass {
  float: right;
  padding: 15px 0;
  margin-right: 20px;
  font-size: 13px;
  cursor: pointer;
  color: #b1b1b1;
}
.orderclass:hover {
  color: #f22e00;
}
.span-a {
  font-size: 12px;
  float: right;
  padding: 15px 0;
  cursor: pointer;
  color: #6376a8;
}
.span-a:hover {
  color: #f22e00;
}
.imgtd {
}
</style>
